package net.butfly.bus.server.config.impl;

import net.butfly.bus.config.bean.ConnectionBean;
import net.butfly.bus.config.bean.NodeBean;
import net.butfly.bus.config.bean.NodeInvokerBean;
import net.butfly.bus.config.bean.RouterBean;
import net.butfly.bus.config.bean.TimeoutBean;
import net.butfly.bus.config.bean.TxBean;
import net.butfly.bus.context.Constants;
import net.butfly.bus.exception.BusRuntimeException;
import net.butfly.bus.server.ServerConfigInterface;

import com.caucho.hessian.client.HessianProxyFactory;
import com.rb.econsole.service.EConsoleNodeBean;
import com.rb.econsole.service.EConsoleNodeContainerBean;
import com.rb.econsole.service.EConsoleNodeJoinBean;
import com.rb.econsole.service.EConsoleTxBean;
import com.rb.econsole.service.IEConsoleService;

public class ConfigHessianImp implements ServerConfigInterface {
	private IEConsoleService service;

	private String hessianPath;

	public ConfigHessianImp(String hessianPath) {
		this.hessianPath = hessianPath;
	}

	private IEConsoleService getService() {
		if (service == null) {
			HessianProxyFactory factory = new HessianProxyFactory();
			try {
				service = (IEConsoleService) factory.create(IEConsoleService.class, hessianPath);
			} catch (Exception e) {
				throw new BusRuntimeException(Constants.UserError.CONFIG_ERROR, "连接Hessian " + hessianPath + " 异常", e);
			} catch (Error e) {
				throw new BusRuntimeException(Constants.UserError.CONFIG_ERROR, "连接Hessian " + hessianPath + " 错误", e);
			}
		}
		return service;
	}

	public NodeBean getNodeBean(String nodeId) {
		IEConsoleService service = getService();
		if (service != null) {
			EConsoleNodeBean nodeBean = service.getNodeBeanById(nodeId);
			if (nodeBean != null) {
				EConsoleNodeJoinBean entb = nodeBean.getJoin();
				ConnectionBean ntb = null;
				if (entb != null) {
					ntb = new ConnectionBean(entb.getId(), entb.getType(), entb.getConfig());
				}

				EConsoleNodeContainerBean encb = nodeBean.getContainer();
				NodeInvokerBean ncb = null;
				if (encb != null) {
					ncb = new NodeInvokerBean(encb.getId(), encb.getType(), encb.getConfig());
				}
				return new NodeBean(nodeBean.getId(), null, ntb, ncb, nodeBean.getConfig());
			}
		}
		return null;
	}

	public RouterBean getRouterBean() {
		return new RouterBean("default", "simple", "random");// 默认路由器
	}

	public String[] getNodeIDsByMatching(String txCode) {
		IEConsoleService service = getService();
		if (service != null) {
			return service.getNodeIdAryByTxMatching(txCode);
		}
		return null;
	}

	public TxBean getTxBean(String code, String version) {
		IEConsoleService service = getService();
		if (service != null) {
			EConsoleTxBean etb = service.getTxBean(code, version);
			if (etb != null) {
				return new TxBean(etb.getCode(), etb.getVersion(), etb.getNodeAry());
			}
		}
		return null;
	}

	public TimeoutBean getTimeoutBean(String code) {
		return null;
	}
}
